package com.sc.app.security.openidauth;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.social.connect.UsersConnectionRepository;
import org.springframework.social.security.SocialUserDetails;
import org.springframework.social.security.SocialUserDetailsService;
import org.springframework.stereotype.Component;

/**
 * @author sc
 * Created on  2018/1/24
 */
@Component
public class OpenIdAuthSecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain,HttpSecurity>{
    @Autowired
    private AuthenticationSuccessHandler authSuccessHandler;
    @Autowired
    private AuthenticationFailureHandler authFailHandler;
    @Autowired
    private SocialUserDetailsService userDetails;
    @Autowired
    private UsersConnectionRepository usersConnectionRepository;

    @Override
    public void configure(HttpSecurity http) throws Exception {
        OpenIdAuthFilter openIdAuthFilter = new OpenIdAuthFilter();
        openIdAuthFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
        openIdAuthFilter.setAuthenticationSuccessHandler(authSuccessHandler);
        openIdAuthFilter.setAuthenticationFailureHandler(authFailHandler);
        OpenIdAuthProvider authProvider = new OpenIdAuthProvider();
        authProvider.setUserDetailsService(userDetails);
        authProvider.setUsersConnectionRepository(usersConnectionRepository);

        http.authenticationProvider(authProvider).addFilterAfter(openIdAuthFilter, UsernamePasswordAuthenticationFilter.class);
    }
}
